﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UIWindow.Helper;
using UIWindow.Lucifer;

namespace UIWindow.Protocols.Fins
{
    public class ResponseReadWrite : IProtocol
    {
        /// <summary>
        /// 标头
        /// </summary>
        public string Head { get; set; }
        /// <summary>
        /// 包长度
        /// </summary>
        public int DataLength { get; set; }
        /// <summary>
        /// 命令码
        /// </summary>
        public int Cmd { get; set; }
        /// <summary>
        /// 错误代码
        /// </summary>
        public int Error { get; set; }
        /// <summary>
        /// 错误代码
        /// </summary>
        public byte[] EndCodes { get; set; }
        /// <summary>
        /// 读的时候有数据，写的时候没有，所以需要判断读写
        /// </summary>
        public List<ushort> DataList { get; set; }
        public int Length { get; set; }

        public byte[] GetStream()
        {
            return null;
        }

        /// <summary>
        /// 解析数据
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public IProtocol Handle(byte[] bytes)
        {
            if (bytes.Length < 8) return null;
            if (bytes.Length < bytes.Skip(4).Take(4).ToArray().ByteToInt()) return null;
            DataList = new List<ushort>();
            EndCodes = new byte[2];
            Head = bytes.Take(4).ToArray().ASCIIToString();
            DataLength = bytes.Skip(4).Take(4).ToArray().ByteToInt();
            Cmd = bytes.Skip(8).Take(4).ToArray().ByteToInt();
            Error = bytes.Skip(12).Take(4).ToArray().ByteToInt();
            EndCodes[0] = bytes[28];
            EndCodes[1] = bytes[29];
            if (bytes[27] == 0x01)
            {
                DataList.Clear();
                for (int i = 30; i < bytes.Length; i += 2)
                {
                    DataList.Add(ByteToUShort(bytes[i], bytes[i + 1]));
                }
            }
            return this;
        }
        private ushort ByteToUShort(byte one, byte tow) => (ushort)((one << 8) + tow);
    }
}
